import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { LocalizationService } from '@abp/ng.core';
import { FilterGroupDto, FilterRuleDto } from '../../proxy/joy/erp/basic-archives/core/filters/models';
import { FilterGroupOperate } from '../../proxy/joy/erp/basic-archives/core/filters/filter-group-operate.enum';
import { FilterRuleOperate } from '../../proxy/joy/erp/basic-archives/core/filters/filter-rule-operate.enum';

@Component({
  selector: 'lib-advanced-filter-dialog',  
  templateUrl: './advanced-filter-dialog.component.html',
  styleUrls: ['./advanced-filter-dialog.component.less'],
})
export class AdvancedFilterDialogComponent implements OnInit {
  @Input() entityConfig: any;
  @Input() filterGroup: FilterGroupDto;
  @ViewChild('inputElement', { static: false }) inputElement?: ElementRef;

  isAdding = false;
  schemeName = '';
  savedSchemes: Array<{name: string, filterGroup: FilterGroupDto}> = [];
  currentScheme: {name: string, filterGroup: FilterGroupDto} | null = null;

  validateForm: FormGroup;
  FilterGroupOperate = FilterGroupOperate;
  FilterRuleOperate = FilterRuleOperate;
  
  // 转换枚举为下拉选项
  filterRuleOperateOptions = Object.keys(FilterRuleOperate)
    .filter(key => !isNaN(Number(FilterRuleOperate[key])))
    .map(key => ({
      label: key,
      value: FilterRuleOperate[key]
    }));

  constructor(
    private fb: FormBuilder,
    private modal: NzModalRef,
    private localizationService: LocalizationService,
    private message: NzMessageService
  ) {}

  ngOnInit(): void {
    this.loadSavedSchemes();
    this.initForm();
    if (this.filterGroup) {
      this.loadFilterGroup(this.filterGroup);
    }
  }

  private loadSavedSchemes() {
    const savedData = localStorage.getItem(`advancedFilterSchemes::${this.entityConfig.entityType}`);
    if (savedData) {
      this.savedSchemes = JSON.parse(savedData);
    }
  }

  private saveSchemes() {
    localStorage.setItem(`advancedFilterSchemes::${this.entityConfig.entityType}`, JSON.stringify(this.savedSchemes));
  }

  showInput(): void {
    this.isAdding = true;
    setTimeout(() => {
      this.inputElement?.nativeElement?.focus();
    }, 10);
  }

  handleInputConfirm(): void {
    if (this.schemeName && this.validateForm.valid) {
      const formValue = this.validateForm.value;
      const filterGroup = this.transformGroupWithFilter(formValue);

      // 检查是否已存在同名方案
      if (this.savedSchemes.some(s => s.name === this.schemeName)) {
        this.message.error(this.l('BasicArchives::UI:AdvancedFilterDialog.Message.SchemesNameAlreadyExists'));
        return;
      }

      this.savedSchemes.push({
        name: this.schemeName,
        filterGroup: filterGroup
      });
      this.saveSchemes();
      this.currentScheme = this.savedSchemes[this.savedSchemes.length - 1];
    }
    this.schemeName = '';
    this.isAdding = false;
  }

  loadScheme(scheme: {name: string, filterGroup: FilterGroupDto}): void {
    // 如果点击的是当前选中的方案，则更新该方案
    if (this.currentScheme?.name === scheme.name) {
      const formValue = this.validateForm.value;
      const filterGroup = this.transformGroupWithFilter(formValue);
      
      // 更新方案
      const index = this.savedSchemes.findIndex(s => s.name === scheme.name);
      if (index !== -1) {
        this.savedSchemes[index] = {
          name: scheme.name,
          filterGroup: filterGroup
        };
        this.saveSchemes();
        this.message.success(this.l('BasicArchives::UI:AdvancedFilterDialog.Message.SchemesUpdateSuccess'));
      }
    } else {
      // 首次点击，加载方案
      this.currentScheme = scheme;
      
      // 重置表单
      this.initForm();
      
      // 加载新的查询条件
      this.loadFilterGroup(scheme.filterGroup);
    }
  }

  deleteScheme(scheme: {name: string, filterGroup: FilterGroupDto}, e: MouseEvent): void {
    e.stopPropagation();
    this.savedSchemes = this.savedSchemes.filter(s => s.name !== scheme.name);
    this.saveSchemes();
    if (this.currentScheme?.name === scheme.name) {
      this.currentScheme = null;
    }
  }

  private initForm() {
    this.validateForm = this.fb.group({
      operate: [FilterGroupOperate.And],
      rules: this.fb.array([]),
      groups: this.fb.array([])
    });
  }

  private loadFilterGroup(filterGroup: FilterGroupDto) {
    // 清空现有的规则和组
    while (this.rules.length) {
      this.rules.removeAt(0);
    }
    while (this.groups.length) {
      this.groups.removeAt(0);
    }

    // 设置操作符
    this.validateForm.patchValue({ operate: filterGroup.operate });

    // 加载规则
    filterGroup.rules?.forEach(rule => {
      let fieldName = rule.property;
      // 检查是否是日期类型的字段
      const property = this.entityConfig?.propertys.find(p => p.name === rule.property.replace('.Date', ''));
      if (property?.type?.toLowerCase() === 'date' || property?.type?.toLowerCase() === 'datetime') {
        fieldName = rule.property.replace('.Date', '');
      }

      const ruleForm = this.fb.group({
        field: [fieldName],
        operate: [rule.operate],
        value: [rule.value]
      });
      this.rules.push(ruleForm);
    });

    // 递归加载子组
    filterGroup.groups?.forEach(group => {
      const groupForm = this.createGroupForm(group);
      this.groups.push(groupForm);
    });
  }

  private createGroupForm(group: FilterGroupDto): FormGroup {
    const groupForm = this.fb.group({
      operate: [group.operate],
      rules: this.fb.array([]),
      groups: this.fb.array([])
    });

    // 加载规则
    const rulesArray = groupForm.get('rules') as FormArray;
    group.rules?.forEach(rule => {
      let fieldName = rule.property;
      // 检查是否是日期类型的字段
      const property = this.entityConfig?.propertys.find(p => p.name === rule.property.replace('.Date', ''));
      if (property?.type?.toLowerCase() === 'date' || property?.type?.toLowerCase() === 'datetime') {
        fieldName = rule.property.replace('.Date', '');
      }

      const ruleForm = this.fb.group({
        field: [fieldName],
        operate: [rule.operate],
        value: [rule.value]
      });
      rulesArray.push(ruleForm);
    });

    // 递归加载子组
    const groupsArray = groupForm.get('groups') as FormArray;
    group.groups?.forEach(nestedGroup => {
      groupsArray.push(this.createGroupForm(nestedGroup));
    });

    return groupForm;
  }

  get rules() {
    return this.validateForm.get('rules') as FormArray;
  }

  get groups() {
    return this.validateForm.get('groups') as FormArray;
  }

  addRule() {
    const ruleForm = this.fb.group({
      field: [''],
      operate: [FilterRuleOperate.Equal],
      value: ['']
    });
    this.rules.push(ruleForm);
  }

  removeRule(index: number) {
    this.rules.removeAt(index);
  }

  addGroup() {
    const groupForm = this.fb.group({
      operate: [FilterGroupOperate.And],
      rules: this.fb.array([]),
      groups: this.fb.array([])
    });
    this.groups.push(groupForm);
  }

  removeGroup(index: number) {
    this.groups.removeAt(index);
  }

  cancel() {
    // 重置表单
    this.initForm();
    
    // 清空当前选中的方案
    this.currentScheme = null;
  }

  submitForm() {
    if (!this.validateForm.valid) return;
    
    // 转换表单值为FilterGroupDto结构并过滤无效规则
    const formValue = this.validateForm.value;
    const filterGroup = this.transformGroupWithFilter(formValue);
    
    this.modal.close(filterGroup);
  }

  private hasValidConditions(group: FilterGroupDto): boolean {
    return (group.rules && group.rules.length > 0) || 
           (group.groups && group.groups.length > 0);
  }

  private transformGroupWithFilter(group: any): FilterGroupDto {
    const rules = this.transformRulesWithFilter(group.rules || []);
    const groups = (group.groups || [])
      .map(g => this.transformGroupWithFilter(g))
      .filter(g => this.hasValidConditions(g));

    return {
      operate: group.operate,
      rules: rules,
      groups: groups
    };
  }

  private transformRulesWithFilter(rules: any[]): FilterRuleDto[] {
    if (!rules) return [];
    
    return rules
      .filter(rule => {
        // 如果value不为空，则property必须有值
        if (rule.value) {
          return !!rule.field;
        }
        // 如果value为空，则整条rule无效
        return false;
      })
      .map(rule => {
        // 检查是否是日期类型的字段
        const property = this.entityConfig?.propertys.find(p => p.name === rule.field);
        let propertyName = rule.field;
        
        // 如果是日期类型，添加 .Date 后缀
        if (property?.type?.toLowerCase() === 'date' || property?.type?.toLowerCase() === 'datetime') {
          propertyName = `${propertyName}.Date`;
        }

        return {
          property: propertyName,
          operate: rule.operate,
          value: rule.value
        };
      });
  }

  protected l(key: string): string {
    return this.localizationService.instant(key);
  }

  toggleOperate() {
    const currentOperate = this.validateForm.get('operate').value;
    const newOperate = currentOperate === FilterGroupOperate.And ? 
      FilterGroupOperate.OrElse : FilterGroupOperate.And;
    this.validateForm.patchValue({ operate: newOperate });
  }

  getOperateLabel(index: number) {
    if (index === 0) return null;
    return FilterGroupOperate[this.validateForm.get('operate').value];
  }
} 